<?php
// 应用公共文件
use GuzzleHttp\Client;
use think\facade\View;
use think\facade\Db;
use liliuwei\think\Auth;
use think\facade\Session;
function w_log($uid=0,$pid='',$str='',$info="",$ctype=""){
    if($pid=='' || $str==""){

    }else{
        DB::name("log")->insert(['uid'=>$uid,'pid'=>$pid,'content'=>$str,'info'=>$info,'ctype'=>$ctype,'addtime'=>date("Y/m/d H:i:s")]);
    }
}
function getUserGroup(){
    $res = DB::name("admin_group")->where("status",1)->select();
    return $res;
}
function gettoken(){
    $tokenjson=file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx315aca5fc8cc56dc&secret=5e598a84b1dc1a6f63980df0a3a5c21c");
    $tokenjson=json_decode($tokenjson,true);
//    var_dump($tokenjson['access_token']);
    if(isset($tokenjson['access_token'])){
        $token=$tokenjson['access_token'];
        DB::name('token')->where("title",'token')->update(['content'=>$token,'uptime'=>time()]);
        return $token;
    }else{
        return false;
    }
}

function r_class($id=0){//获取id下所有子目录,不包含自己
    $ids=[];
    $class=DB::name("category")->field("id")->where("classid",$id)->select();
    if($class){
        foreach ($class as $v){
            $ids[]=$v['id'];
            $erji=r_class($v['id']);
            if($erji){
                $ids=array_merge($ids,$erji);
            }
        }
        return $ids;
    }else{
        return false;
    }
}
function r_class_all(){
    $class=DB::name("category")->select();
    return $class;
}
function r_admin_all($where=''){
    if($where!=""){
        $class=DB::name("admin")->where($where)->select();
    }else{
        $class=DB::name("admin")->select();
    }
    return $class;
}

function r_class2_all(){
    $class=DB::name("category2")->select();
    return $class;
}
function classidToClassname($class,$id){
    if($id == "" || $id ==null){
        return '';
    }
    foreach ($class as $v){
        if($v['id']==$id){
            return $v['classname'];
        }
    }
    return $id;
}
function rClassIdToTitle($id=0){
    $re = r_one("classes","id=$id");
    if($re){
        return $re['title'];
    }else{
        return "";
    }
}

function adminIDToUserName($class,$id){
    if($id == "" || $id ==null){
        return '';
    }
    foreach ($class as $v){
        if($v['id'] == $id){
            return $v['fullname'];
        }
    }
    return $id;
}
function userIDToUserName($id=0){
	if($id==0) return "system";
    $user = DB::name("users")->where("id",$id)->column("username");
	if($user) return $user[0];
	return $id;
}
function serviceIDToName($id=0){
	if($id==0) return "null";
    $user = DB::name("service")->where("id",$id)->column("title");
	if($user) return $user[0];
	return $id;
}
function gasIDToName($id=0){
	if($id==0) return "";
    $user = DB::name("gas")->where("id",$id)->column("name");
	if($user) return $user[0];
	return $id;
}
function supplierIDToTitle($id=0){
	if($id==0) return "";
    $user = DB::name("supplier")->where("id",$id)->column("title");
	if($user) return $user[0];
	return $id;
}
function r_group($int=0){
    if($int==0){
        $res=DB::name("auth_group")->select();
    }else{
        $res=DB::name("auth_group")->where("id",$int)->find();
        if(!$res){echojson([],1,"组不存在");}
    }
    return $res;
}
function getuser($int=0){
    if($int==0) {
        $uid = Session::get("uid");
    }else{
        $uid=$int;
    }
    $user=DB::name("admin")->where("id",$uid)->find();
    if($user){
        return [$uid,$user['classid'],$user];
    }else{
        header('Location: /mlogin/login?t=tip');
        exit();
    }
}

function r_one($table,$where='',$order="id desc"){
    if($where==''){
        $re = DB::name($table)->order($order)->find();
        return $re;
    }
    $re = DB::name($table)->where($where)->order($order)->find();
    return $re;
}
function r_all($table,$where='',$order="id desc"){
    if($where==''){
        $re = DB::name($table)->order($order)->select();
        return $re;
    }
    $re = DB::name($table)->where($where)->order($order)->select();
    return $re;
}
/**
 * @param $int 大于0就查询分类的之类集合
 * @param $inids 数组或字符查询inids
 * @return array|\think\Collection|Db[]
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function r_classes($int=0,$inids=false,$field='',$order=''){
    $res=DB::name("classes");
    if($int>0){
        $res =  $res->where("pathid",$int);
    }
    if($inids!==false){
        $res = $res->whereIn("id",$inids);
    }
    if($field!==''){
        $res = $res->field($field);
    }
    if($order==''){
        $res = $res->where("status",1)->order("sortid desc,id asc")->select();
    }else{
        $res = $res->where("status",1)->order($order)->select();
    }
    if(!$res){echojson([],1,"配置不存在");}
    return $res;
}
function sishewuru($num=0,$n=2){
	return  round(floatval($num),2);
}
function r_classesRule($str=0,$inids=false,$field='',$order=''){
    $res=DB::name("classes");
    if($str!=''){
        $res =  $res->where("rule",$str);
    }
    if($inids!==false){
        $res = $res->whereIn("id",$inids);
    }
    if($field!==''){
        $res = $res->field($field);
    }
    if($order==''){
        $res = $res->where("status",1)->order("sortid desc,id asc")->select();
    }else{
        $res = $res->where("status",1)->order($order)->select();
    }
    if(!$res){echojson([],1,"配置不存在");}
    return $res;
}
function getOrderNo(){
	list($usec, $sec) = explode(" ", microtime());
	return "JZX".date("YmdHis").\think\helper\Str::random(12,1);
}
function rclassesToclasses($int=0){//读取2级数据，不需要树形结构
    $reArr=[];
    $res=DB::name("classes")->where("pathid",$int)->select();
    foreach ($res as $v){
        $reArr[]=$v;
        $res2=DB::name("classes")->where("pathid",$v['id'])->select();
        if($res2){
            foreach ($res2 as $v2){
                $reArr[]=$v2;
            }
        }
    }
    return $reArr;
}


function r_user($userid=''){
    $user=DB::name("admin")->alias("a")->field("a.*,b.dingID,b.title,b.pathID")->leftJoin("admin_group b","a.classid = b.id")->where("a.id",$userid)->find();
    if(!$user || $userid==""){
        $user['fullname']="未知";
        $user['mobile']="-";
    }
    return $user;
}
function rusers($id=0,$lock=false){
	if($lock==true){
		$user=DB::name("users")->lock(true)->where("id",$id)->find();
	}else{
		$user=DB::name("users")->where("id",$id)->find();
	}
	return $user;
}
function getOrderStatus($cint=0){
	if($cint==0) return "下单";
	if($cint==1) return "上游下单";
	if($cint==2) return "待支付";
	if($cint==3) return "已支付";
	if($cint==4) return "已支付";
	if($cint==-1) return "上游下单失败";
	if($cint==-2) return "生成支付失败";
	if($cint==-3) return "未支付";
	if($cint==-4) return "已退款";
}
function getGasStatus($cint=0){
	if($cint==0)return "添加";
	if($cint==1)return "正在营业";
	if($cint==2)return "暂停营业";
	if($cint==3)return "停止营业";
	if($cint==4)return "修建中";
}
function distance($lat1, $lon1, $lat2, $lon2) {
    // 将角度转换为弧度
    $degToRad = M_PI / 180;

    // 地球平均半径（单位：米）
    $earthRadius = 6371000;

    // 将经纬度转换为弧度
    $lat1 *= $degToRad;
    $lon1 *= $degToRad;
    $lat2 *= $degToRad;
    $lon2 *= $degToRad;

    // Haversine公式计算距离
    $dLat = ($lat2 - $lat1);
    $dLon = ($lon2 - $lon1);
    $a = pow(sin($dLat/2), 2) + cos($lat1) * cos($lat2) * pow(sin($dLon/2), 2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $distance = $earthRadius * $c;

    return round($distance, 2); // 返回结果保留小数点后两位
}



function name_to_user($userid=''){
    $user=DB::name("admin")->where("username",$userid)->find();
    if(!$user || $userid==""){
        $user['fullname']="未知";
        $user['id']=0;
    }
    return $user;
}

function upload(){
    //开始上传
    $arr=[];
    $file = request() -> file('file');
    if(!isset($_FILES["file"])){echojson([],1,"上传失败");}
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if(!in_array(strtolower($extension), array("jpg","jpeg","png","xls","xlsx","doc","docx","ppt","pptx","pdf","zip","rar"))){
        echojson([],1,"不合法后缀");
    }

    $saveName = \think\facade\Filesystem::disk('photo') -> putFile('photo', $file, 'md5');
    $path=str_replace('\\', '/', '/uploads/' . $saveName);
    return $path;
    //上传结束
}
function r_users(){
    $user=DB::name("admin")->field("id,fullname")->select();
    return $user;
}
function lock($table=''){
    $model = DB::startTrans();
    return $model;
}
function unlockCommit($model=''){
    DB::commit();
}
function unlockRollback($model=''){
    DB::rollback();
}
function nowTime(){
    return date("Y-m-d H:i:s");
}
function nowDate(){
    return date("Y-m-d");
}
function nowMicrotime(){
	return (int) round(microtime(true)*1000);
}
function yesterday(){
    return date("Y-m-d",strtotime("-1 day"));
}
function dayAgo($int=0){
    return date("Y-m-d",strtotime("$int day"));
}
function appImg($a=""){
	if(is_array($a)){
		foreach ($a as $k=>$v){
			$a[$k] = apiURLHTTP().apiURL()."/".trim($v,"/");
		}
	}
	if(is_string($a)){
		foreach (explode(",",$a) as $k=>$v){
			$a[$k] = apiURLHTTP().apiURL()."/".trim($v,"/");
		}
	}
	return $a;
}
function r_log_uid($pid=0,$ctype=''){//获取初审人uid
    if($pid==0 || $ctype==""){
        return false;
    }
    $log=DB::name("log")->where("pid",$pid)->where("ctype",$ctype)->where("content","1")->select();
    return $log;
}
function rTipsToServiceIDS($tips){
	$tipsArr = DB::name("service")->whereIn("tipsID",$tips)->column("id");
	return implode(",",$tipsArr);
}
/**读取多个油站标签并集 的ids
 * @param $tips
 * @return string
 */
function rTipsToIds2($tips='0'){
	//求ids的集合  并集
	$tipsArr = DB::name("tips")->whereIn("id",$tips)->column("ids");
	$temArr=[0];
	foreach ($tipsArr as $v){
		if($v!="" && $v!=null){
			$v = explode(",",$v);
			$temArr = array_merge($temArr, $v);
		}
	}
	return implode(",",$temArr);
}

/**读取一个标签的ids
 * @param $tips
 * @return mixed|string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function rTipsToIds($tips){
	$res = DB::name("tips")->where("id",$tips)->find();
	if($res){
		$ids = $res['ids'];
		if(strlen($ids)>0){
			return $ids;
		}
	}
	return "0";
}
function rIdsToTips($ids='0'){
	$res = DB::name("tips")->whereIn("id",$ids)->column("title");
	return implode(",",$res);
}
function rclasstitle($class=[],$tid=0){//从config配置中选出匹配的id 返回title
    if($tid==1){
//        return '其他';
    }
    if($tid == "" || $tid ==null){
        return '';
    }
    foreach ($class as $v){
        if($v['id']==$tid){
            return $v['title'];
        }
    }
    return $tid;
}
function idToClassTitle($id=0){//用classid读取title
    $re = r_one("classes","id=".$id);
    if(!$re){return "";}
    return $re['title'];
}
function RClassID($class=[],$title=''){//从config配置中选出匹配的title 返回ID
    foreach ($class as $v){
        if(isset($v['title'])){
            if($v['title']==$title){
                return $v['id'];
            }
        }else{
            return '';
        }
    }
    return '';
}
function r_config($int=0,$inids=false){
    if($int==0){
        if($inids!==false){
            $res=DB::name("config")->where("pathid",0)->where("id","in",$inids)->select();
        }else{
            $res=DB::name("config")->where("pathid",0)->select();
        }
    }else{
        if($inids!==false){
            $res=DB::name("config2")->where("tid",$int)->where("id","in",$inids)->select();
        }else{
            $res=DB::name("config2")->where("tid",$int)->select();
        }

        if(!$res){echojson([],1,"配置不存在");}
    }
    return $res;
}
function checkTimeAdd($uid,$tid){
    $hospitalid  = 0 ;
    $hospitalid2  = 0 ;
    if($tid>0){
        $task = DB::name("task")->where("id",$tid)->find();
        if($task){
            $hospitalid = $task['hospitalid'];
        }
    }else{
        echojson([],1,'任务ID错误');
    }
    $pra_re = DB::name("orders")->where("uid",$uid)->order("id desc")->find();
    if($pra_re){
        $task2 = DB::name("task")->where("id",$pra_re['tid'])->find();
        if($task2){
            $hospitalid2 = $task2['hospitalid'];
        }
        if($hospitalid2 == $hospitalid &&  (time()-strtotime($pra_re['addtime'])) < 900 ){
            echojson([],1,'间隔需15分钟以上');
        }elseif($hospitalid2 != $hospitalid &&  (time()-strtotime($pra_re['addtime'])) < 3600 ){
            echojson([],1,'间隔需1小时以上');
        }

    }
}

function message_sign(){
	return '【铁壳测试】';
}
function send_message($mobile,$msg){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send.json");

	curl_setopt($ch, CURLOPT_HTTP_VERSION  , CURL_HTTP_VERSION_1_0 );
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_HEADER, FALSE);

	curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);
	curl_setopt($ch, CURLOPT_USERPWD  , 'api:key-774ed5a0c');

	curl_setopt($ch, CURLOPT_POST, TRUE);
	curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => $mobile,'message' => $msg.message_sign()));

	$res = curl_exec( $ch );
	curl_close( $ch );
	$json = json_decode($res,true);
	if($json['error']==0){
		return true;
	}else{
		echojson([],1,$json['msg']);
	}
}
function checkMobile($phone) {
	$pattern = "/^1[3-9]\d{9}$/";
	return preg_match($pattern, $phone);
}
/**
 * @param int $int  int=0读取pathid为0的select >0读取单独ID：find
 * @param int $i    i>0自动拆分title的第几个数组内容
 * @return array|mixed|string|\think\Collection|Db|Db[]|\think\Model|null
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function r_config2($int=0,$i=0){
    if($int==0){
        $res=DB::name("config2")->where("pathid",0)->select();
    }else{
        $res=DB::name("config2")->where("id",$int)->find();
        if(!$res){echojson([],1,"配置不存在");}
    }
    if($i>0){
        $res=explode(",",$res['title'])[$i-1];
    }
    return $res;
}

function r_config2_id($id=0){
    $res=DB::name("config2")->where("id",$id)->find();
    return $res;
}
function r_config2_in_id($ids=[]){
    $res=DB::name("config2")->whereIn("id",$ids)->select();
    return $res;
}

function r_rule($int=0){
    if($int==0){
        $res=DB::name("auth_rule")->select();
    }else{
        $res=DB::name("auth_rule")->where("id",$int)->find();
        if(!$res){echojson([],1,"权限不存在");}
    }
    return $res;
}
function r_url_type($url){
    $re=DB::name("auth_rule")->where("name",$url)->find();
    if(!$re){
        return false;
    }
    if($re['classty']==1){
        return ["function",$re['title']];
    }else{
        return ["page",$re['title']];
    }
}
function r_rule2($int=0){
    if($int==0){
        $res=DB::name("classes")->select();
    }else{
        $res=DB::name("classes")->where("id",$int)->find();
        if(!$res){echojson([],1,"配置不存在");}
    }
    return $res;
}
function clasesToRule($classes=[],$int=0){
   foreach ($classes as $v){
	   if($v['id']==$int) return $v['rule'];
   }
    return null;
}
function checkUserToken($token=''){
    $re = r_one("admin","token='$token' and status=1");
    return $re;
}

function checkuser(){
    $token = request()->param("token");
	$post = request()->param();
    if(strlen($token) != 32){
        $uid=Session::get("uid");
    }else{
        $admin = checkUserToken($token);
        if(!$admin){echojson([],1,'验证错误');}
        $uid = $admin['id'];
        if(Session::get("uid") < 1){
            Session::set("uid",$uid);
            Session::set("admin",$admin['fullname']);
        }
    }

//    var_dump($uid);exit();
//    return true;
    $auth=new Auth();
    $controller = strtolower(request()->controller());
    $action = strtolower(request()->action());
    $url = $controller . "/" . $action;
    $liwai=['index/login'];
    if(!in_array($url,$liwai)){
		$have = DB::name("auth_rule")->where("name",$url)->find();
        $re=$auth->check("admin/all", $uid);
        if(!$re){
            $re=$auth->check($url, $uid);
        }
        $urltype=r_url_type($url);
		if($urltype){
			if (!$re) {
				if($uid){
					if($urltype[0]=="page"){
						View::assign(['message'=>$urltype[1].' 无访问权限']);
						$html = View::fetch("404/404");
						echo $html;
						exit();
						return "404";
					}else{
						echojson([],1,$urltype[1]." 已登录但无该页面操作权限，请联系管理员。");
					}
				}else{
					if($urltype[0]=="page"){
						Session::set('url', $url);
						header('Location:/mlogin/login?t=tip');
					}else{
						echojson([],1,"尚未登陆或已超时");
					}
				}
			}else{
				//没登陆跳转登陆
				if(!$uid){
					Session::set('url', $url);
					header('Location:/mlogin/login?t=tip');
				}
			}
		}
    }
	$re=DB::name("auth_rule")->where("name",$url)->find();
	if($re){
		if($re['log']==1){
			w_log($uid,$re['title'],"成功",$url,json_encode($post,JSON_UNESCAPED_UNICODE));
		}
	}else{
		w_log($uid,$url,"成功",$url,json_encode($post,JSON_UNESCAPED_UNICODE));
	}
}
function substr_cut($user_name=''){
    //获取字符串长度
    $strlen = mb_strlen($user_name, 'utf-8');
    //如果字符创长度小于2，不做任何处理
    if($strlen<2){
        return $user_name;
    }else{
        //mb_substr — 获取字符串的部分
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
        //str_repeat — 重复一个字符串
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }
}
function apiURL(){
    return "//gas.zhissf.com";
}
function apiURLHTTP(){
    return "https:";
}
function echojson($arr=[], $error=0, $content="操作成功",$end=1){
    if($error!=0){
        unlockRollback('');
    }else{
        unlockCommit('');
    }
    header('content-type:application/json;charset=utf-8');
    $temarr=[
        'code'=>$error,
        'msg'=>$content,
        'data'=>$arr
    ];
    print_r(json_encode($temarr,JSON_UNESCAPED_UNICODE));
    if($end==1){
        exit();
    }
}
function pagejson($arr=[],$error=0,$content="",$count=0){
    header('content-type:application/json;charset=utf-8');
    $temarr=[
        'code'=>$error,
        'msg'=>$content,
        'count'=>$count,
        'data'=>$arr
    ];
    print_r(json_encode($temarr));
    exit();
}
function rand_md5(){
    return md5(uniqid(microtime(true),true));
}
function rand_10Str(){
    return substr(rand_md5(),0,10);
}
//普通curlpost
function curlPost($url='',$data=[],$headers = ['Content-Type: application/json'])
{
    $log = new \app\Log("curl_post");
	$ch = curl_init($url);
	if ($ch === false) {
		return false;
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	if (!empty($headers)) {
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	}

	$t=0;
	if($t==1){
		curl_setopt($ch, CURLOPT_VERBOSE, true);
		curl_setopt($ch, CURLOPT_HEADER, true);
		$verbose = fopen('php://temp', 'w+');
		curl_setopt($ch, CURLOPT_STDERR, $verbose);
	}


	$response = curl_exec($ch);
	if (curl_errno($ch)) {
		curl_close($ch); // 关闭 curl 资源
		return false;
	}

	if($t==1){
	    $info = curl_getinfo($ch);
        $log->write(['res'=>$info,'url'=>$url,'data'=>$data,'headers'=>$headers]);
// 		rewind($verbose);
// 		$verboseLog = stream_get_contents($verbose);
// 		fclose($verbose);
// 		echo "=== cURL 详细调试信息 ===\n";
// 		echo $verboseLog;

// 		$info = curl_getinfo($ch);
// 		print_r($info);

// 		echo "=== cURL 提交参数 ===\n";
// 		print_r($data);
// 		echo "\n=== 响应内容 ===\n" . $response;
	}
    $log->write(['res'=>$response,'url'=>$url,'data'=>$data,'headers'=>$headers]);
	curl_close($ch);
	return $response;
}


/** 用户微信支付和退款
 * @param $url
 * @param $xml_data
 * @param $cert
 * @return bool|string
 */
function post_xml($url='',$xml_data='',$cert=false){
    $ch = curl_init($url);
    $header[] = "Content-type: text/xml";//定义content-type为xml
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);

    if($cert){
        //此处证书引用绝对路径 微信退款需要
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
        curl_setopt($ch, CURLOPT_SSLCERT, '/www/ssl/ssssssss/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
        curl_setopt($ch, CURLOPT_SSLKEY, '/www/ssl/sssssss/apiclient_key.pem');
    }

    $response = curl_exec($ch);
    if(curl_errno($ch))
    {
//        print curl_error($ch);
    }
    curl_close($ch);
    return $response;
}
function arr_to_xml($data, $root = true)
{
    $str = "";
    if ($root) {
        $str .= "<xml>";
    }
    foreach ($data as $key => $val) {
        if (is_array($val)) {
            $child = arr_to_xml($val, false);
            $str .= "<$key>$child</$key>";
        } else {
            $str .= "<$key><![CDATA[$val]]></$key>";
        }
    }
    if ($root) {
        $str .= "</xml>";
    }
    return $str;
}
function imgAndHttp($arr=[]){
    if(!is_array($arr)){return $arr;}
    foreach ($arr as $k=>$v){
        $arr[$k]=apiURLHTTP().apiURL().$v;
    }
    return $arr;
}
function getpagedata($table,$field="",$return=false,$where=''){
    $page=request()->param("page");
    $limit=request()->param("limit");
    $page<1?$page=1:'';
    $limit<1?$limit=10:'';
    $count=DB::name($table)->where($where)->count();
    if($count<1){
        pagejson([],0,"",0);
    }
    $pages=ceil($count/$limit);
//	$page = $page>$pages?$pages:$page;
    if($field!=""){
        $lists=DB::name($table)->field($field)->where($where)->order("id desc")->limit((($page-1)*$limit),$limit)->select();
    }else{
        $lists=DB::name($table)->where($where)->order("id desc")->limit((($page-1)*$limit),$limit)->select();
    }
    if($return==true){
        return [$lists,$count];
    }
    pagejson($lists,0,"",$count);
}
function getRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';
    for ($i = 0; $i < $length; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
    return substr(sha1($string), 0, $length);
}
/**
 * 计算两点地理坐标之间的距离
 * @param Decimal $longitude1 起点经度
 * @param Decimal $latitude1 起点纬度
 * @param Decimal $longitude2 终点经度
 * @param Decimal $latitude2 终点纬度
 * @param Int   $unit    单位 1:米 2:公里
 * @param Int   $decimal  精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=1){

	$EARTH_RADIUS = 6370.996; // 地球半径系数
	$PI = 3.1415926;

	$radLat1 = $latitude1 * $PI / 180.0;
	$radLat2 = $latitude2 * $PI / 180.0;

	$radLng1 = $longitude1 * $PI / 180.0;
	$radLng2 = $longitude2 * $PI /180.0;

	$a = $radLat1 - $radLat2;
	$b = $radLng1 - $radLng2;

	$distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
	$distance = $distance * $EARTH_RADIUS * 1000;

	if($unit==2){
		$distance = $distance / 1000;
	}

	return round($distance, $decimal);

}

/**
 * 将数值金额转换为中文大写金额
 * @param $amount float 金额(支持到分)
 * @param $type   int   补整类型,0:到角补整;1:到元补整
 * @return mixed 中文大写金额
 */
function convertAmountToCn($amount, $type = 0) {
    // 判断输出的金额是否为数字或数字字符串
    if(!is_numeric($amount)){
        return "要转换的金额只能为数字!";
    }

    // 金额为0,则直接输出"零元整"
    if($amount == 0) {
        return "人民币零元整";
    }

    // 金额不能为负数
    if($amount < 0) {
        return "要转换的金额不能为负数!";
    }

    // 金额不能超过万亿,即12位
    if(strlen($amount) > 12) {
        return "要转换的金额不能为万亿及更高金额!";
    }

    // 预定义中文转换的数组
    $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    // 预定义单位转换的数组
    $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');

    // 将金额的数值字符串拆分成数组
    $amountArr = explode('.', $amount);

    // 将整数位的数值字符串拆分成数组
    $integerArr = str_split($amountArr[0], 1);

    // 将整数部分替换成大写汉字
    $result = '人民币';
    $integerArrLength = count($integerArr);     // 整数位数组的长度
    $positionLength = count($position);         // 单位数组的长度
    for($i = 0; $i < $integerArrLength; $i++) {
        // 如果数值不为0,则正常转换
        if($integerArr[$i] != 0){
            $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
        }else{
            // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
            if(($positionLength - $integerArrLength + $i + 1)%4 == 0){
                $result = $result . $position[$positionLength - $integerArrLength + $i];
            }
        }
    }

    // 如果小数位也要转换
    if($type == 0) {
        // 将小数位的数值字符串拆分成数组
        $decimalArr = str_split($amountArr[1], 1);
        // 将角替换成大写汉字. 如果为0,则不替换
        if($decimalArr[0] != 0){
            $result = $result . $digital[$decimalArr[0]] . '角';
        }
        // 将分替换成大写汉字. 如果为0,则不替换
        if($decimalArr[1] != 0){
            $result = $result . $digital[$decimalArr[1]] . '分';
        }
    }else{
        $result = $result . '整';
    }
    return $result;
}
